var common = require('/common.js')
function loginRequest(requestInfo, successCallBack, failedCallBack) {
  wx.request({
    url: common.baseBurl+'/account/ajaxLogin',
    data: requestInfo,
    header: {},
    method: 'POST',
    dataType: 'json',
    responseType: 'text',
    success: function(res) {
      if (successCallBack && successCallBack instanceof Function) {
        if (typeof(res) != 'undefined' && res != null) {
          successCallBack(res.data);
          wx.setStorage({
            key: 'loginInfo',
            data: res.data,
          })
        }
      }
    },
    fail: function(res) {
      if (failedCallBack && failedCallBack instanceof Function) {
        if (typeof(res) != 'undefined' && res != null) {
          failedCallBack(res.data)
        }
      }
    },
    complete: function(res) {},
  })
}



function loginOut(successCallBack, failedCallBack) {
  getRequest('account/logout', '', 'GET', function(res) {
    if (typeof(res) != 'undefined' && res != null) {
      successCallBack(res);
      if (res.success) {
        wx.clearStorage();
      }
    }
  }, failedCallBack);
}



function getRequest(requestUrl, requestBody, requestType, successCallBack, failedCallBack) {
  wx.getStorage({
    key: 'loginInfo',
    success: function(res) {
      var cookieStr = res.data.data.sessionkey;
      requestService(cookieStr, requestUrl, requestBody, requestType, successCallBack, failedCallBack);
    },
    fail(res) {
      console.log(res.data);
    }
  })
}


function requestService(cookieStr, requestUrl, requestBody, requestType, successCallBack, failedCallBack) {
  wx.request({
    url: common.baseBurl + requestUrl,
    data: requestBody,
    header: {
        'Cookie': 'JSESSIONID=' + cookieStr
    },
    method: requestType,
    dataType: 'json',
    responseType: 'text',
    success: function(res) {
      if (successCallBack && successCallBack instanceof Function) {
        if (typeof(res) != 'undefined' && res != null) {
          successCallBack(res.data);
        }
      }
    },

    fail: function(res) {
      if (failedCallBack && failedCallBack instanceof Function) {
        if (typeof(res) != 'undefined' && res != null) {
          failedCallBack(res.data)
        }
      }
    },
    complete: function(res) {},

  })

}




module.exports = {

  getRequest: getRequest,

  loginRequest: loginRequest,

  loginOut: loginOut

}